<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
    description("Tests concurrent calls to many crypto operations happening on workers as well as main thread.");

    // This test runs web crypto operations on 11 "threads".
    //   * The main thread (this page)
    //   * 10 web workers
    //
    // The code for each thread is in "resources/subtle-crypto-concurrent.js"
    // and runs multiple parallel crypto operations.
    //
    // The intent of this test is to try an exercise any races in the WebCrypto
    // code, and make sure operations work from workers.

    jsTestIsAsync = true;

    function createPromiseForThread(thread, hookOnError) {
        return new Promise(function(resolve, reject) {
            thread.onmessage = function(event)
            {
                if (event.data == "TEST_FINISHED") {
                    debug("Thread completed successfully");
                    resolve();
                    resolve = null;
                } else {
                    debug("Unexpected message: " + event.data);
                    reject();
                }
            };

            if (hookOnError) {
                thread.onerror = function(event)
                {
                    debug("Thread failed: " + event.data);
                    reject();
                };
            }
        });
    }

    function createPromiseForWorker()
    {
        var worker = new Worker("resources/subtle-crypto-concurrent.js");
        return createPromiseForThread(worker, true);
    }

    function createPromiseForMainThread()
    {
        return createPromiseForThread(self, false);
    }

    var allPromises = [];
    for (var i = 0; i < 10; ++i)
        allPromises.push(createPromiseForWorker());

    // The worker script is included at the end of this page too, so it
    // performs the same work as the workers.
    allPromises.push(createPromiseForMainThread(self));

    Promise.all(allPromises).then(finishJSTest, failAndFinishJSTest);
</script>
<script src="resources/subtle-crypto-concurrent.js"></script>
</body>
</html>
